<ANTARTIFACTLINK identifier="test-page" type="text/html" title="Robot WebSocket Test Interface" isClosed="true" />

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Robot WebSocket Test</title>
    <style>
        body { font-family: Arial, sans-serif; padding: 20px; }
        .container { max-width: 1200px; margin: 0 auto; }
        .panel { border: 1px solid #ddd; padding: 15px; margin: 10px 0; border-radius: 4px; }
        .log-panel { height: 300px; overflow-y: scroll; background: #f5f5f5; padding: 10px; }
        .status { padding: 10px; margin: 5px 0; }
        .success { color: green; }
        .error { color: red; }
        .message { margin: 5px 0; padding: 5px; border-bottom: 1px solid #eee; }
        .grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
    </style>
</head>
<body>
    <div class="container">
        <h1>Robot WebSocket Test Interface</h1>

        <!-- 认证面板 -->
        <div class="panel">
            <h3>1. Authentication</h3>
            <div>
                <button onclick="login()">Login (Get Token)</button>
                <span id="auth-status" class="status">Not authenticated</span>
            </div>
        </div>

        <!-- WebSocket 连接面板 -->
        <div class="panel">
            <h3>2. WebSocket Connection</h3>
            <div>
                <button onclick="connectWebSocket()">Connect WebSocket</button>
                <button onclick="disconnectWebSocket()">Disconnect</button>
                <span id="ws-status" class="status">Disconnected</span>
            </div>
        </div>

        <!-- 机器人连接面板 -->
        <div class="panel">
            <h3>3. Robot Connection</h3>
            <div>
                <input type="text" id="robot-ip" placeholder="Robot IP" value="192.168.58.128">
                <input type="text" id="robot-port" placeholder="Port" value="8055">
                <button onclick="connectToRobot()">Connect to Robot</button>
                <span id="robot-status" class="status">Not connected</span>
            </div>
        </div>

        <div class="grid">
            <!-- 命令测试面板 -->
            <div class="panel">
                <h3>4. Test Commands</h3>
                <div>
                    <button onclick="sendTestCommand('SystemInfoGroup')">Query System Info</button>
                    <button onclick="sendTestCommand('PeriphInfoGroup')">Query Periph Info</button>
                    <button onclick="sendTestCommand('custom')">Send Custom Command</button>
                </div>
                <div>
                    <h4>Custom Command:</h4>
                    <textarea id="custom-command" rows="4" style="width: 100%">
{
    "type": "SystemInfoGroup",
    "data": { "query": {} }
}
                    </textarea>
                </div>
            </div>

            <!-- 日志面板 -->
            <div class="panel">
                <h3>5. Message Log</h3>
                <div id="log-panel" class="log-panel"></div>
                <button onclick="clearLog()">Clear Log</button>
            </div>
        </div>
    </div>

    <script>
        let ws = null;
        let token = null;

        function log(message, type = 'info') {
            const logPanel = document.getElementById('log-panel');
            const entry = document.createElement('div');
            entry.className = `message ${type}`;
            entry.textContent = `${new Date().toLocaleTimeString()} - ${message}`;
            logPanel.appendChild(entry);
            logPanel.scrollTop = logPanel.scrollHeight;
        }

        function clearLog() {
            document.getElementById('log-panel').innerHTML = '';
        }

        async function login() {
            try {
                const response = await fetch('/api/auth/login', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ username: 'admin', password: 'admin' })
                });
                const data = await response.json();
                if (response.ok) {
                    token = data.token;
                    document.getElementById('auth-status').textContent = 'Authenticated';
                    document.getElementById('auth-status').className = 'status success';
                    log('Authentication successful');
                } else {
                    throw new Error(data.message);
                }
            } catch (error) {
                log(`Authentication failed: ${error.message}`, 'error');
                document.getElementById('auth-status').textContent = 'Authentication failed';
                document.getElementById('auth-status').className = 'status error';
            }
        }

        function connectWebSocket() {
            if (!token) {
                log('Please authenticate first', 'error');
                return;
            }

            ws = new WebSocket('ws://10.10.3.27:8081');

            ws.onopen = () => {
                log('WebSocket connected');
                document.getElementById('ws-status').textContent = 'Connected';
                document.getElementById('ws-status').className = 'status success';

                // Send authentication
                ws.send(JSON.stringify({
                    type: 'auth',
                    token: token
                }));
            };

            ws.onmessage = (event) => {
                const data = JSON.parse(event.data);
                log(`Received: ${JSON.stringify(data, null, 2)}`);

                if (data.type === 'auth_success') {
                    log('WebSocket authentication successful');
                }
            };

            ws.onclose = () => {
                log('WebSocket disconnected');
                document.getElementById('ws-status').textContent = 'Disconnected';
                document.getElementById('ws-status').className = 'status error';
            };

            ws.onerror = (error) => {
                log(`WebSocket error: ${error.message}`, 'error');
            };
        }

        function disconnectWebSocket() {
            if (ws) {
                ws.close();
                ws = null;
            }
        }

        function connectToRobot() {
            if (!ws) {
                log('Please connect WebSocket first', 'error');
                return;
            }

            const ip = document.getElementById('robot-ip').value;
            const port = document.getElementById('robot-port').value;
            const robotAddress = `ws://${ip}:${port}`;

            ws.send(JSON.stringify({
                type: 'connect_robot',
                deviceId: 'test-robot-001',
                robotAddress: robotAddress
            }));

            log(`Attempting to connect to robot at ${robotAddress}`);
        }

        function sendTestCommand(type) {
            if (!ws) {
                log('Please connect WebSocket first', 'error');
                return;
            }

            let command;
            if (type === 'custom') {
                try {
                    command = JSON.parse(document.getElementById('custom-command').value);
                } catch (error) {
                    log('Invalid JSON in custom command', 'error');
                    return;
                }
            } else {
                command = {
                    type: type,
                    data: { query: {} }
                };
            }

            ws.send(JSON.stringify({
                type: 'robot_command',
                command: command
            }));

            log(`Sent command: ${JSON.stringify(command)}`);
        }
    </script>
</body>
</html>
